package 算法.leetcode.offer;

import 算法.leetcode.offer.base.ListNode;

/**
 * 输入两个递增排序的链表，合并这两个链表并使新链表中的节点仍然是递增排序的。
 *
 * 示例1：
 *
 * 输入：1->2->4, 1->3->4
 * 输出：1->1->2->3->4->4
 *
 * @author lchenglong
 * @date 2022/3/17
 */
public class Offer25 {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1),next = new ListNode(2),third = new ListNode(3);
        l1.next = next;
        next.next = third;
        ListNode l2 = new ListNode(1),next2 = new ListNode(3),third2 = new ListNode(4);
        l2.next = next2;
        next2.next = third2;
        Offer25 instance = new Offer25();
        ListNode listNode = instance.mergeTwoLists(l1, l2);
        while (listNode!=null){
            System.out.print(listNode.val+",");
            listNode = listNode.next;
        }
    }
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // 边界条件
        if (l1 == null||l2 == null){
            return l1==null?l2:l1;
        }
        ListNode head = new ListNode(0),cur = head;
        while (l1!=null&&l2!=null){
            if (l1.val<=l2.val){
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        cur.next = l1==null?l2:l1;
        return head.next;
    }
}
